package com.hoo.permission.sdk.server.dao.impl;

import com.hoo.common.model.Page;
import com.hoo.permission.sdk.server.dao.ISysRoleDao;
import com.hoo.permission.sdk.server.domain.dto.SysRoleDto;
import com.hoo.permission.sdk.server.domain.entity.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统-角色表 Dao层 实现
 * @author 小韩工作室
 * @date 2020-06-28 16:51:32
 */
@Repository
public class SysRoleDaoImpl implements ISysRoleDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean add(SysRole entity){

        KeyHolder keyHolder = new GeneratedKeyHolder();
        PreparedStatementCreator preparedStatementCreator = con -> {
            PreparedStatement ps = con.prepareStatement("INSERT INTO t_sys_role(role_key, name, description,status) VALUES(?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, entity.getRoleKey());
            ps.setString(2, entity.getName());
            ps.setString(3, entity.getDescription());
            ps.setString(4, entity.getStatus());
            return ps;
        };

        if(jdbcTemplate.update(preparedStatementCreator, keyHolder) > 0) {
            entity.setId(keyHolder.getKey().longValue());
            return true;
        }
        return false;
    }

    @Override
    public boolean update(SysRole entity) {
        return jdbcTemplate.update("UPDATE t_sys_role SET name = ? ,description = ?,status = ?  WHERE  id = ?", entity.getName(), entity.getDescription(), entity.getStatus(), entity.getId()) > 0;
    }


    @Override
    public boolean updateStatus(Long roleId, String status) {
        return jdbcTemplate.update("UPDATE t_sys_role SET status = ?  WHERE  id = ?", status, roleId) > 0;
    }

    @Override
    public boolean delete(SysRole entity){
        // 目前限定 SUPER_ADMIN 超管不可被删除，系统中留作特殊用途
        return jdbcTemplate.update("DELETE FROM t_sys_role WHERE  id= ? AND role_key != 'SUPER_ADMIN'", entity.getId()) > 0;
    }

    @Override
    public boolean delete(Long roleId) {
        SysRole role = new SysRole();
        role.setId(roleId);
        return delete(role);
    }

    @Override
    public SysRole get(Serializable id) {
        List<SysRole> list = jdbcTemplate.query("SELECT id, role_key, name, description,status FROM t_sys_role WHERE id = ? ", new Object[]{ id }, new BeanPropertyRowMapper<SysRole>(SysRole.class));
        if(list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public List<SysRole> findAll(Map<String, Object> params) {
        List<Object> whereVals = new ArrayList<>();
        StringBuilder sql = new StringBuilder("SELECT id, role_key, name, description,status FROM t_sys_role WHERE 1=1 ");
        if (params.containsKey("status")) {
            sql.append(" AND status = ? ");
            whereVals.add(params.get("status"));
        }
        List<SysRole> list = jdbcTemplate.query(sql.toString(), whereVals.toArray(new Object[]{}), new BeanPropertyRowMapper<SysRole>(SysRole.class));
        if(list != null && list.size() > 0) {
            return list;
        }else{
            return new ArrayList<>();
        }
    }

    @Override
    public Page<SysRoleDto> query(Page page, Map<String, Object> params) {
        if (page == null) {
            page = new Page();
        }
        List<Object> whereVals = new ArrayList<>();
        StringBuilder whereSql = new StringBuilder();

        if (params.get("status") != null) {
            whereSql.append(" AND a.status = ? ");
            whereVals.add(params.get("status"));
        }

        if (params.get("searchWord") != null) {
            whereSql.append(" AND (a.name LIKE ? OR a.description LIKE ?) ");
            whereVals.add("%" + params.get("searchWord") + "%");
            whereVals.add("%" + params.get("searchWord") + "%");
        }

        Long total = jdbcTemplate.queryForObject(new StringBuilder("SELECT COUNT(1) FROM t_sys_role a WHERE 1=1 ").append(whereSql).toString(), whereVals.toArray(new Object[]{}), Long.class);

        whereVals.add((page.getPageNo() - 1) * page.getLimit());
        whereVals.add(page.getLimit());
        List<SysRoleDto> list = jdbcTemplate.query(new StringBuilder("SELECT id, role_key, name, description,status,GROUP_CONCAT(b.resource_id) as resource_ids FROM t_sys_role a LEFT JOIN t_sys_role_resource b ON a.id = b.role_id WHERE 1=1").append(whereSql).append(" GROUP BY a.id LIMIT ?,?").toString(), whereVals.toArray(new Object[]{}), new BeanPropertyRowMapper<>(SysRoleDto.class));
        if(list != null && list.size() > 0) {
            page.setRecords(list);
        }
        page.setTotal(total);
        return page;
    }
}
